<template>
  <div class="task-con" :style="{ height: userInfo.jumpFlag != 'erp' ? ' calc(100vh - @menuHeight)' : '100vh' }">
    <div class="top-tab">
      <a-tabs v-model:active-key="curPage" @change="tabChange" size="mini">
        <a-tab-pane v-for="item in tabList" :key="item.key">
          <template #title>
            <span>{{ item.label }}</span>
            <span>({{ item.num ? item.num : '0' }})</span>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>
    <div class="table-bottom table-gl-w">
      <div class="search-w">
        <FilterTable :filterItem="filterItem" :max-num="5" :isReset="true" @search="searchByVal" />
      </div>
      <div class="table-gl-con">
        <TableWrap style="flex: 1" @refresh="getList">
          <template #headerLeft>
            <a-space>
              <!-- <div>合计任务：{{ statictsInfo.sumNum }}条 合计任务费用：￥{{ transNumberToShort(statictsInfo.amtSumAmount, 4) }} </div> -->

              <div v-if="curPage == 'SENDING_SAMPLE'">
                <a-radio-group type="button" v-model="sampleStatus" @change="getList">
                  <a-radio value="WAIT_SEND_SAMPLE">待送样</a-radio>
                  <a-radio value="WAIT_RECEIVE_SAMPLE">待收样</a-radio>
                </a-radio-group>
              </div>

              <a-button @click="startTask('mul')" class="gray-outline" v-if="['WAIT_SCHEDULE'].includes(curPage)">开始执行</a-button>
              <a-button @click="submitTask('mul')" class="gray-outline" v-if="['EXECUTING'].includes(curPage)">提交任务</a-button>
              <a-button @click="handOverTask('mul')" class="gray-outline" v-if="['WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY'].includes(curPage)">移交任务</a-button>
              <a-button @click="WithdrawSendSample('mul')" class="gray-outline" v-if="['WAIT_SCHEDULE'].includes(curPage)">撤回送样中</a-button>
              <a-button @click="WithdrawToDo('mul')" class="gray-outline" v-if="['EXECUTING'].includes(curPage)">撤回待执行</a-button>
              <a-button @click="cancelEpt('mul')" class="gray-outline" v-if="['WAIT_VERIFY'].includes(curPage)">取消验收</a-button>
              <a-button @click="setTag('mul')" class="gray-outline">设置标签</a-button>
              <a-button @click="confirmReceiptSample('mul')" class="gray-outline" v-if="['SENDING_SAMPLE'].includes(curPage)">确认收样</a-button>
            </a-space>
          </template>
          <template #tableBody>
            <a-table size="mini" :bordered="{ headerCell: true, wrapper: true }" v-model:selected-keys="ids" row-key="id" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" class="table-singe-line show-border-tabl" @sorter-change="sortChange" :data="tableList" :loading="loading" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
              <template #columns>
                <a-table-column title="序号" #cell="{ rowIndex }" :width="50" fixed="left">{{ rowIndex + 1 }}</a-table-column>
                <a-table-column title="图片" #cell="{ record }" :width="60" fixed="left">
                  <ImgPopover :src="imgUrl(record)">
                    <template #con>
                      <a-image :preview="false" width="40" height="40" fit="contain" :src="imgUrl(record)" />
                    </template>
                  </ImgPopover>
                </a-table-column>
                <a-table-column title="SKU" #cell="{ record }" :width="150" fixed="left">
                  <TextLimit v-if="$extract(record, 'product.sku')" @click="showSkuDetail(record)" class="highlight cursor" position="top" :rows="1" :val="$extract(record, 'product.sku') || '--'" />
                  <div v-else>--</div>
                </a-table-column>
                <a-table-column title="采购下单" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtPurchase"> {{ $setTime($extract(record, 'product.gmtPurchase'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <a-table-column title="采购入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtPurchaseWarehouse"> {{ $setTime($extract(record, 'product.gmtPurchaseWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <a-table-column title="货件发货" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtShipmentShipped"> {{ $setTime($extract(record, 'product.gmtShipmentShipped'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <a-table-column title="货件入库" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="product.gmtShippmentWarehouse"> {{ $setTime($extract(record, 'product.gmtShippmentWarehouse'), 'YYYY-MM-DD HH:mm') }} </a-table-column>
                <!-- <a-table-column title="任务类型" #cell="{ record }" :width="80">{{ typeMap[record.type] }} </a-table-column> -->
                <a-table-column title="服务内容" #cell="{ record }" :width="80">
                  <TextLimit :val="$extract(record, 'taskRequire.serContent')" :rows="1" position="top" />
                </a-table-column>
                <!-- <a-table-column title="任务费用" #cell="{ record }" :width="80">
                  <div style="color: red">￥{{ $extract(record, 'amtbCost') }}</div>
                </a-table-column> -->

                <a-table-column title="甲方" #cell="{ record }" :width="100"> {{ $extract(record, 'companyShortName') }} </a-table-column>
                <a-table-column title="雇主" #cell="{ record }" :width="100" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="employer.name"> {{ $extract(record, 'employer.name') }} </a-table-column>
                <a-table-column title="类型/ID" #cell="{ record }" :width="160">
                  <div>{{ typeMap[record.type] }}</div>
                  <a-space>
                    <div class="highlight cursor" @click="viewDetial(record)">{{ record.code }}</div>
                    <div v-if="$extract(record.taskRequire, 'isSample')">
                      <span style="color: #979797" class="icon icon-yangpin"></span>
                    </div>
                  </a-space>
                </a-table-column>
                <a-table-column title="任务执行人" #cell="{ record }" :width="100">
                  <div class="task_user" style="width: 100%; height: 100%">
                    <a-space>
                      <TextLimit :val="getExecuterUser(record) || '--'" />
                    </a-space>
                  </div>
                </a-table-column>
                <a-table-column title="预计交付日期" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtPlanDelivery">
                  <div>{{ $setTime(record.gmtPlanDelivery, 'YYYY-MM-DD') }}</div>
                  <div v-if="record.gmtPlanDelivery">
                    <div style="color: red" v-if="!toCheckDay(record.gmtPlanDelivery).type">超时{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                    <div class="highlight" v-else>剩余{{ toCheckDay(record.gmtPlanDelivery).day }}</div>
                  </div>
                </a-table-column>

                <a-table-column title="发布时间" v-if="['WAIT_ACCEPT'].includes(curPage)" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtPublish">
                  {{ $setTime(record.gmtPublish, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>

                <a-table-column v-if="['SENDING_SAMPLE', 'WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY', 'NEGOTIATE_TERMINATED'].includes(curPage)" title="接单时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtTake">
                  {{ $setTime(record.gmtTake, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY', 'NEGOTIATE_TERMINATED'].includes(curPage)" title="到样时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSampleDelivery">
                  {{ $setTime(record.gmtSampleDelivery, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['EXECUTING', 'WAIT_VERIFY', 'NEGOTIATE_TERMINATED'].includes(curPage)" title="排期时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSchedule">
                  {{ $setTime(record.gmtSchedule, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="['WAIT_VERIFY'].includes(curPage)" title="提交时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSubmitVerify">
                  {{ $setTime(record.gmtSubmitVerify, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <a-table-column v-if="curPage != 'SENDING_SAMPLE'" title="完成时间" #cell="{ record }" :width="130" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtFinish">
                  {{ $setTime(record.gmtFinish, 'YYYY-MM-DD HH:mm') }}
                </a-table-column>
                <!-- <a-table-column v-if="curPage == ''" title="状态" #cell="{ record }" :width="130">
                  {{ tabKeyMap[record.status] }}
                </a-table-column> -->

                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送样地址" #cell="{ record }" :width="130">
                  {{ $extract(record, 'sendSample.sampleAddress.stateOrRegion') }}
                  {{ $extract(record, 'sendSample.sampleAddress.city') }}
                  {{ $extract(record, 'sendSample.sampleAddress.address') }}
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送样方式" #cell="{ record }" :width="130">
                  <a-space>
                    <div>{{ record.sendType == 'DOOR_DELIVERY' ? '快递' : '送货上门' }}</div>
                    <!-- <div> <icon-edit /> </div> -->
                  </a-space>
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="送出日期" :sortable="{ sortDirections: ['ascend', 'descend'] }" data-index="gmtSend" #cell="{ record }" :width="130">
                  {{ $setTime($extract(record, 'sendSample.gmtSend'), 'YYYY/MM/DD') }}
                </a-table-column>
                <a-table-column v-if="['SENDING_SAMPLE'].includes(curPage)" title="物流商/跟踪号" #cell="{ record }" :width="130">
                  <div>{{ $extract(record, 'sendSample.logistics') ? $extract(record, 'sendSample.logistics') : '--' }}</div>
                  <div>{{ $extract(record, 'sendSample.trackingNumber') ? $extract(record, 'sendSample.trackingNumber') : '--' }}</div>
                </a-table-column>

                <a-table-column title="标签" #cell="{ record }" :width="140">
                  <div>
                    <a-space wrap>
                      <a-tag size="small" v-for="tag in record.tagList" :key="tag.id" :color="tag.color">{{ tag.name }}</a-tag>
                      <div class="cursor" @click="setTag('single', record)"><icon-edit /></div>
                    </a-space>
                  </div>
                </a-table-column>

                <a-table-column title="留言" #cell="{ record }" :width="80">
                  <a-space>
                    <div>{{ getNum(record.leaveMsgList) }}</div>
                    <div>
                      <div v-if="record.hasPartaNewLeaveMsg == null || record.hasPartaNewLeaveMsg == false">
                        <icon-message @click="showMsgModal(record)" class="cursor" :style="{ fontSize: '18px' }" />
                      </div>
                      <div v-else>
                        <a-badge :count="1" dot :offset="[2, -2]">
                          <icon-message @click="showMsgModal(record)" class="cursor" :style="{ color: '#f59a23', fontSize: '18px', verticalAlign: '-3px' }" />
                        </a-badge>
                      </div>
                    </div>
                  </a-space>
                </a-table-column>
                <a-table-column title="操作" #cell="{ record }" :width="100" fixed="right">
                  <a-space>
                    <a-button type="text" @click="viewDetial(record)">详情</a-button>
                    <a-dropdown trigger="hover">
                      <icon-more class="highlight" style="font-size: 28px" />
                      <template #content>
                        <a-doption @click="startTask('single', record)" v-if="['WAIT_SCHEDULE'].includes(record.status)">开始执行</a-doption>
                        <a-doption @click="submitTask('single', record)" v-if="['EXECUTING'].includes(record.status)">提交任务</a-doption>
                        <a-doption @click="handOverTask('single', record)" v-if="['WAIT_SCHEDULE', 'EXECUTING', 'WAIT_VERIFY'].includes(record.status)">移交任务</a-doption>
                        <a-doption @click="WithdrawSendSample('single', record)" v-if="['WAIT_SCHEDULE'].includes(record.status) && record.taskRequire.isSample">撤回送样中</a-doption>
                        <a-doption @click="WithdrawToDo('single', record)" v-if="['EXECUTING'].includes(record.status)">撤回待执行</a-doption>
                        <a-doption @click="cancelEpt('single', record)" v-if="['WAIT_VERIFY'].includes(record.status)">取消验收</a-doption>
                        <a-doption @click="negotiate(record)" v-if="['NEGOTIATE_TERMINATED'].includes(record.status)">协商</a-doption>

                        <a-doption @click="confirmReceiptSample('single', record)" v-if="['SENDING_SAMPLE'].includes(record.status)">确认收样</a-doption>
                      </template>
                    </a-dropdown>
                  </a-space>
                </a-table-column>
              </template>
            </a-table>
          </template>
        </TableWrap>
        <div class="pagination-footer">
          <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
        </div>
      </div>
    </div>
  </div>
  <msglist v-if="showMsgListModal" v-model="showMsgListModal" :info="taskDetailInfo" @save="getList" />
  <!-- 详情 -->
  <viewTaskDetail v-if="viewTaskDetailModal" v-model="viewTaskDetailModal" isTeamtype="isTeam" :info="taskDetailInfo" @save="getList" />
  <!-- 移交任务 -->
  <turnOverTask v-if="showTurnOverTaskModal" v-model="showTurnOverTaskModal" :ids="setType == 'mul' ? ids : [id]" @save="getList" />
  <!-- 确认收到样品 -->
  <confirmRecSample v-if="showConfirmReceiptSampleModal" v-model="showConfirmReceiptSampleModal" :ids="setType == 'mul' ? ids : [id]" @save="getList" />
  <!-- 标签 -->
  <tag ref="Tag" :dataList="editShowTagList" :idList="ids" @save="tagSave" />
  <!-- 协商任务 -->
  <negotiateTask v-if="showNegotiateTaskModal" v-model="showNegotiateTaskModal" :info="taskDetailInfo" @save="getList" />
  <!-- sku详情 -->
  <skuDetail ref="SKU" :info="taskDetailInfo" />
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { findMyTaskPage, countMyTaskStatus, listByParam, statTaskFromLocation, secondPartyStartTask, cancelVerifyTask, submitVerifyTask, rollbackToSendingSample, rollbackToWaitSchedule } from '@/api/task'
  import { Message, Modal } from '@arco-design/web-vue'
  import { transNumberToShort } from '@/utils'
  import useUserStore from '@/store/modules/user'
  import FilterTable from '@/components/TableFilter.vue'
  import TableWrap from '@/components/TableWrap.vue'
  import msglist from './components/msgList.vue'
  import viewTaskDetail from './components/viewDetail/viewdetailIndex.vue'
  import turnOverTask from './components/handOverTask.vue'
  import confirmRecSample from './components/confirmReceiptSample.vue'
  import negotiateTask from './components/negotiateTask.vue'
  import tag from './components/tag/tagList.vue'
  import skuDetail from './components/skuDetail.vue'
  import _ from 'lodash-es'
  const typeMap = {
    NEW_PRODUCT_PICTURE: '新品套图',
    FIX_PICTURE: '以图修图',
    SHOOT_VIDEO: '拍摄视频',
    POSTER_SHOP_DESIGN: '海报设计',
    CHANGE_DIAMOND_COLOR: '换钻调色',
    HAND_DRAWN_DESIGN: '手绘设计',
  }
  const Tag = ref()
  const SKU = ref()
  let curPage = ref('WAIT_SCHEDULE')
  let tabList = ref([
    { label: '送样中', num: '0', key: 'SENDING_SAMPLE' },
    { label: '待执行', num: '0', key: 'WAIT_SCHEDULE' },
    { label: '执行中', num: '0', key: 'EXECUTING' },
    { label: '待验收', num: '0', key: 'WAIT_VERIFY' },
    { label: '协商终止', num: '0', key: 'NEGOTIATE_TERMINATED' },
    { label: '全部任务', num: '0', key: '' },
  ])
  let statictsInfo: any = ref({})
  let searchValue: any = ref({})
  let tableList = ref([{}])
  let loading = ref(false)
  let showMsgListModal = ref(false)
  let viewTaskDetailModal = ref(false)
  let showTurnOverTaskModal = ref(false)
  let showConfirmReceiptSampleModal = ref(false)
  let showNegotiateTaskModal = ref(false)
  let id = ref()
  let ids: any = ref([])
  let setType = ref('')
  let taskType: any = ref('')
  let sampleStatus: any = ref('')
  let taskDetailInfo: any = ref({})
  let editShowTagList: any = ref([])
  let pageNation = ref({ total: 0, pageNum: 1, pageSize: 20 })
  let userInfo = useUserStore()
  const filterItem: any = ref([
    {
      type: 'input_keyword',
      key: 'serContentList',
      keyItems: [
        { label: '任务ID', value: 'codeList' },
        { label: '服务内容', value: 'serContentList' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '服务内容',
      width: 200,
      isMultiple: true,
    },
    {
      type: 'input_keyword_type',
      key: 'product.sku',
      keyItems: [
        { label: '产品SKU', value: 'product.sku' },
        { label: '产品SPU', value: 'product.spu' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '产品SKU',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'employerName',
      keyItems: [
        { label: '甲方', value: 'employerName' },
        { label: '雇主', value: 'createUname' },
        { label: '任务执行人', value: 'executerId' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '甲方',
      width: 160,
    },
    {
      key: 'taskType',
      label: '任务类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '新品套图', value: 'NEW_PRODUCT_PICTURE' },
        { label: '以图修图', value: 'FIX_PICTURE' },
        { label: '拍摄视频', value: 'SHOOT_VIDEO' },
        { label: '海报/店招设计', value: 'POSTER_SHOP_DESIGN' },
      ],
      attrs: {
        'allow-clear': true,
      },
    },

    {
      key: 'tagCodeList',
      label: '任务标签',
      value: ref(),
      type: 'select_multiple',
      width: '100%',
      optionItems: [],
      attrs: {
        'allow-clear': true,
      },
    },

    {
      type: 'keyword_date_range_custom',
      key: 'gmtPlanDelivery',
      keyItems: [{ label: '预计交付日期', value: 'gmtPlanDelivery' }],
      keyWidth: '110',
      value: ref(),
      label: '预计交付日期',
      width: 200,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtTake',
      keyItems: [
        { label: '接单时间', value: 'gmtTake' },
        { label: '到样时间', value: 'gmtSampleDelivery' },
      ],
      keyWidth: '110',
      label: '接单时间',
      value: ref(),
      width: 200,
    },
    {
      type: 'keyword_date_range_custom',
      key: 'gmtPurchase',
      keyItems: [
        { label: '采购下单时间', value: 'product.gmtPurchase' },
        { label: '采购入库时间', value: 'product.gmtPurchaseWarehouse' },
        { label: '货件发货时间', value: 'product.gmtShipmentShipped' },
        { label: '货件入库时间', value: 'product.gmtShippmentWarehouse' },
      ],
      keyWidth: '110',
      label: '采购下单时间',
      value: ref(),
      width: 200,
    },
  ])

  const searchByVal = (info: any) => {
    searchValue.value = _.cloneDeep(info)
    console.log(info)

    if (searchValue.value.startDate) {
      searchValue.value.startDate = new Date(`${searchValue.value.startDate} 00:00:00`).valueOf()
      searchValue.value.endDate = new Date(`${searchValue.value.endDate} 23:59:59`).valueOf()
    }
    if (searchValue.value.codeList) {
      searchValue.value.codeList = searchValue.value.codeList.split(',')
    } else {
      searchValue.value.codeList = []
    }
    getList()
  }
  const changePage = (val: number) => {
    pageNation.value.pageNum = val
    getList()
  }

  const sizeChange = (val: number) => {
    pageNation.value.pageNum = 1
    pageNation.value.pageSize = val
    getList()
  }

  const sortChange = (item: any, extra: any) => {
    if (extra) {
      searchValue.value.sortField = item
      searchValue.value.sortAsc = extra == 'ascend' ? true : false
    } else {
      searchValue.value.sortField = ''
      searchValue.value.sortAsc = ''
    }
    getList()
  }

  const getList = async () => {
    let params = {
      ...searchValue.value,
      status: curPage.value,
      pageNum: pageNation.value.pageNum,
      pageSize: pageNation.value.pageSize,
    }
    if (params.status == 'SENDING_SAMPLE') {
      params.sampleStatus = sampleStatus.value
    }
    loading.value = true
    const res: any = await findMyTaskPage(params)
    if (res) {
      tableList.value = res?.data?.records
      pageNation.value.total = res?.data?.total
    }
    ids.value = []
    getStatusNum()
    loading.value = false
  }

  const toCheckDay = (time: any) => {
    let date = new Date(time).valueOf() + 24 * 60 * 60 * 1000
    let newDate = new Date().valueOf()
    let timeStr = 0
    if (date > newDate) {
      timeStr = date - newDate
    } else {
      timeStr = newDate - date
    }
    const formatTimeFromTimestamp = (timestamp: number) => {
      let text = ''
      const days = Math.floor(timestamp / (60 * 60 * 24 * 1000))
      const hours = Math.floor((timestamp % (60 * 60 * 24 * 1000)) / (60 * 60 * 1000))
      text = days > 0 ? `${days}天${hours}小时` : `${Math.abs(hours)}小时`
      return text
    }
    if (date - newDate < 0) {
      return {
        type: false,
        day: formatTimeFromTimestamp(timeStr),
      }
    } else {
      return {
        type: true,
        day: formatTimeFromTimestamp(timeStr),
      }
    }
  }

  const getNum = (list: any) => {
    if (list && list instanceof Array) {
      return list.length > 99 ? '99+' : list.length
    } else {
      return '0'
    }
  }

  const showModal = (type: string, info?: any) => {
    taskType.value = type
    taskDetailInfo.value = info
    showTaskDetailModal.value = true
  }

  const viewDetial = (info: any) => {
    taskDetailInfo.value = info
    viewTaskDetailModal.value = true
  }

  const tabChange = () => {
    pageNation.value.pageNum = 1
    getList()
  }

  const showMsgModal = (info: any) => {
    taskDetailInfo.value = info
    showMsgListModal.value = true
  }

  const imgUrl = (data: any) => {
    let arr = data?.product?.productPicList || []
    return arr.length > 0 ? arr[0].url : ''
  }

  const getStaticsInfo = async () => {
    let params = {
      ...searchValue.value,
      status: curPage.value,
      statLocation: 'J_MY_TASK',
    }
    if (params.status == 'SENDING_SAMPLE') {
      params.sampleStatus = sampleStatus.value
    }
    const res: any = await statTaskFromLocation(params)
    if (res) {
      statictsInfo.value = res?.data || {}
    }
  }

  const getTagList = async () => {
    const res: any = await listByParam({ source: 'TASK' })
    let arr = res.data || []
    arr.map((e: any) => {
      e.label = e.name
      e.value = e.code
      return e
    })
    filterItem.value[4].optionItems = arr
  }

  const getStatusNum = async () => {
    const res: any = await countMyTaskStatus(searchValue.value)
    if (res) {
      tabList.value[0].num = res?.data?.sendingSampleNum || 0
      tabList.value[1].num = res?.data?.waitScheduleNum || 0
      tabList.value[2].num = res?.data?.executingNum || 0
      tabList.value[3].num = res?.data?.waiteVerifyNum || 0
      tabList.value[4].num = res?.data?.negotiateTerminatedNum || 0
      tabList.value[5].num = res?.data?.allNum || 0
    }
  }

  const getExecuterUser = (arr: any) => {
    let newArr = arr?.executerList || []
    return newArr.map((item: any) => item.name).join(',')
  }

  // 开始执行
  const startTask = async (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要开始执行的数据')
    }
    Modal.info({
      title: '提示',
      content: '请再次确认是否要开始执行任务',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const params = {
          idList: type == 'mul' ? ids.value : [data.id],
        }
        const res: any = await secondPartyStartTask(params)
        if (res) {
          Message.success('任务开始执行成功')
          if (type == 'mul') ids.value = []
          getList()
        }
      },
    })
  }
  // 移交任务
  const handOverTask = async (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要移交任务的数据')
    }
    setType.value = type
    type != 'mul' ? (id.value = data.id) : ''
    showTurnOverTaskModal.value = true
  }
  // 撤回待送样
  const WithdrawSendSample = async (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要撤回待送样的数据')
    }

    Modal.info({
      title: '提示',
      content: '请再次确认是否要将任务状态修改为撤回待送样',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const params = {
          idList: type == 'mul' ? ids.value : [data.id],
        }
        const res: any = await rollbackToSendingSample(params)
        if (res) {
          Message.success('撤回成功')
          if (type == 'mul') ids.value = []
          getList()
        }
      },
    })
  }
  // 撤回待执行
  const WithdrawToDo = async (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要撤回到待执行的数据')
    }
    Modal.info({
      title: '提示',
      content: '请再次确认是否要将任务状态修改为待执行',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const params = {
          idList: type == 'mul' ? ids.value : [data.id],
        }
        const res: any = await rollbackToWaitSchedule(params)
        if (res) {
          Message.success('状态修改成功')
          if (type == 'mul') ids.value = []
          getList()
        }
      },
    })
  }
  // 取消验收
  const cancelEpt = async (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要取消验收的数据')
    }
    Modal.info({
      title: '提示',
      content: '请再次确认是否要取消验收，取消之后任务撤回到执行中',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const params = {
          idList: type == 'mul' ? ids.value : [data.id],
        }
        const res: any = await cancelVerifyTask(params)
        if (res) {
          Message.success('取消验收成功')
          if (type == 'mul') ids.value = []
          getList()
        }
      },
    })
  }
  // 提交任务
  const submitTask = async (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要提交任务的数据')
    }
    Modal.info({
      title: '提示',
      content: '请再次确认是否要提交任务',
      titleAlign: 'start',
      cancelText: '取消',
      hideCancel: false,
      onOk: async () => {
        const params = {
          idList: type == 'mul' ? ids.value : [data.id],
        }
        const res: any = await submitVerifyTask(params)
        if (res) {
          Message.success('提交任务成功')
          if (type == 'mul') ids.value = []
          getList()
        }
      },
    })
  }
  // 确认收到样品
  const confirmReceiptSample = (type: string, data?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要确认收样的数据')
    }
    setType.value = type
    type != 'mul' ? (id.value = data.id) : ''
    showConfirmReceiptSampleModal.value = true
  }

  const setTag = (type: string, info?: any) => {
    if (type == 'mul' && !ids.value[0]) {
      return Message.error('请选择需要设置标签的任务')
    }
    if (type != 'mul') ids.value.push(info.id)
    editShowTagList.value = []
    tableList.value.forEach((item: any) => {
      if (ids.value.indexOf(item.id) > -1) {
        if (item.tagList) editShowTagList.value = [...editShowTagList.value, ...item.tagList]
      }
    })

    console.log(editShowTagList.value)

    Tag.value.visible = true
  }

  const negotiate = (info: any) => {
    taskDetailInfo.value = info
    showNegotiateTaskModal.value = true
  }

  const tagSave = () => {
    ids.value = []
    setTimeout(() => {
      getList()
    }, 1000)
  }

  const showSkuDetail = (info: any) => {
    taskDetailInfo.value = info
    SKU.value.visible = true
  }

  onMounted(() => {
    getList()
    getTagList()
    // 统计
    // getStaticsInfo()
  })
</script>

<style lang="less" scoped>
  :deep(.arco-radio-group-button) {
    padding: 0;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 30px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 5px 0 0 5px;
      }
      &:last-child {
        border-radius: 0 5px 5px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }

  .task-con {
    // height: calc(100vh - @menuHeight);
    .top-tab {
      background-color: white;
    }
    .table-bottom {
      height: calc(100vh - @menuAndTabHeight);
    }
  }

  .level-btn {
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    font-size: 12px;
  }

  .level-1 {
    background-color: #ffff80;
    color: black;
  }
  .level-2 {
    background-color: #a30014;
    color: white;
  }
  .level-3 {
    background-color: #d9001b;
    color: white;
  }
  .level-4 {
    background-color: #ec808d;
    color: white;
  }
</style>
